<?php
/**
 * Created by PhpStorm.
 * User: LRChang
 * Date: 2018/8/15
 * Time: 14:58
 */


namespace app\unit\controller;

use think\Db;

class User Extends Base
{
    protected $id = 'user_id';
    protected $table = 'user';
    protected $join = ['role r','m.role_id = r.role_id','left'];
    protected $field = 'm.*,r.role_name';

    //列表
    public function index() {

        $where = $this->search();
        //列表
        $list = $this->joins()->where($where)->where('m.delete_time',$where['m.delete_time'])->order($this->id.' DESC')->fetchSql(0)->paginate(10,false,[
            'query' => input('param.')
        ]);

        $this->assign('list',$list);
        $this->assign('pager',$list->render());

        //弹出层搜索
        $this->_op();

        return $this->out();

    }

    protected function search() {

        $where = [];
        $role = input('param.role_id');
        $filter = input('param.filter');
        $username = input('param.username');

        $role &&  $where['m.role_id'][] = ['=',"$role" ];
        $username &&  $where['m.username'] = ['like',"%$username%" ];
        $filter == 'delete' && $where['m.delete_time'] = ['>',0];

        //非超级管理员
//        if($this->user['role_id'] != 1) {
//            $where['m.role_id'][] = ['<>',1];
//        }

        $where['m.company_id'] = $this->company['company_id'];

        $this->options($where);

        return $where;

    }
    //状态
    public function state() {

        $id = input('post.id/d');
        $state = input('post.state/d');

        if($id) {

            $key = $this->state ?: 'state';
            $rslt = Db::name($this->table)->where($this->id,$id)->fetchSql(0)->setField($key,$state);
        }

        return $this->res($rslt);

    }

    //添加
    public function add() {

        if(request()->isPost()) {

            $data = $this->data();
            $id = Db::name($this->table)->insertGetId($data);
            //发送短信
            if($id) {
                $params = array ();
                // *** 需用户填写部分 ***
                // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
                $accessKeyId = "LTAIBVa52ezFVxQQ";
                $accessKeySecret = "yH32TJNVAverIZdErQk3nAtwIVH5v6";

                // fixme 必填: 短信接收号码
                $params["PhoneNumbers"] = $data['mobile'];

                // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
                $params["SignName"] = "晋江出行";

                // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
                $params["TemplateCode"] = "SMS_127157948";

                // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
                $params['TemplateParam'] = Array (
                    "name" => $data['username'],
                    "password" => input('param.password'),
                );


                // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
                if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
                    $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
                }

                // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
                $helper = new \Tool\signaturehelper();

                // 此处可能会抛出异常，注意catch
                $content = $helper->request(
                    $accessKeyId,
                    $accessKeySecret,
                    "dysmsapi.aliyuncs.com",
                    array_merge($params, array(
                        "RegionId" => "cn-hangzhou",
                        "Action" => "SendSms",
                        "Version" => "2017-05-25",
                    ))
                );

            }
            //更新缓存
            return $this->res($id?1:0 ,[ 'msg' => '','data'=>$id],'index');
        }
        //选项
        $this->options();

        return $this->out();

    }

    public function chgpwd() {

        if(request()->isPost()) {

            $P  = input('post.');
            $rule = [
                'old_password'  => 'require|min:6|max:16',
                'password'  => 'require|confirm|alphaDash|min:6|max:16',
            ];
            $rslt = $this->validate($P,$rule);
            if(true !== $rslt) {
                return $this->error($rslt);
            }

            //旧密码
            if( CorePwd($P['old_password'],$this->user['salt']) != $this->user['password'] ) {
                return $this->error('旧密码错误');
            }

            $data['salt'] = substr(uniqid(), -6);#新盐
            $data['password'] = CorePwd($P['password'],$data['salt']);#新密码

            $rslt = Db::name('user')->where('user_id',$this->uid)->update($data);

            return $this->res($rslt,'',1);


        }

        return $this->out();

    }

    //日记
    public function log() {

        $list = Db::name('UserLog')->alias('l')->join('user u','u.user_id = l.user_id')->order('datetime DESC')->paginate(10);

        $this->assign('list',$list);
        $this->assign('pager',$list->render());

        return $this->out();

    }

    protected function validData($data = []) {

        //分
        $where = $data[$this->id] ? [$this->id=> ['<>',$data[$this->id] ]] : [];
        $repeat = Db::name('user')->where($where)->whereNull('delete_time')->where(function($query) use($data) {
            $query->whereOr('username',$data['username'])->whereOr('mobile',$data['mobile']);
        })->fetchSql(0)->find();

        if($repeat) {
            $msg = $repeat['username'] == $data['username'] ? '用户名已经存在' : '手机号已经存在';
            return $this->error($msg);
        }
    }


    protected function parseData($data = []) {

        if($data['password']) {
            $data['salt'] = substr(uniqid(), -6);
            $data['password'] = CorePwd($data['password'],$data['salt']);
        }

        $data['company_id'] = $this->company['company_id'];
        return $data;
    }

    protected function options($item = []) {

        $roles = Db::name('role')->whereNull('delete_time')->column('role_name','role_id');

        $this->assign('roles',$roles);
        $this->assign('role_ids',TplOptions($roles,$item['role_id']));

        return $item;

    }

}
